package com.example.neutonote2.ui.settings;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.neutonote2.R;
import com.example.neutonote2.utils.DeepseekUtils;
import com.example.neutonote2.utils.DebugUtils;
import com.google.android.material.textfield.TextInputLayout;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * DeepSeek API设置界面
 */
public class DeepseekSettingsFragment extends Fragment {
    private static final String TAG = "DeepseekSettings";
    private static final String API_BASE_URL = "https://api.deepseek.com/beta";
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    private TextInputLayout layoutApiKey;
    private EditText editApiKey;
    private Button btnSave;
    private Button btnTest;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = null;
        try {
            root = inflater.inflate(R.layout.fragment_deepseek_settings, container, false);

            // 初始化视图
            layoutApiKey = root.findViewById(R.id.layout_api_key);
            editApiKey = root.findViewById(R.id.edit_api_key);
            btnSave = root.findViewById(R.id.btn_save_api_key);
            btnTest = root.findViewById(R.id.btn_test_api);
            
            if (layoutApiKey == null || editApiKey == null || btnSave == null || btnTest == null) {
                // 视图ID不匹配，使用备用布局
                Log.e(TAG, "视图ID不匹配，某些控件未找到");
                Toast.makeText(requireContext(), "界面加载错误，请联系开发者", Toast.LENGTH_LONG).show();
                return root;
            }

            // 加载已保存的API密钥
            String savedApiKey = DeepseekUtils.getApiKey(requireContext());
            if (!savedApiKey.isEmpty()) {
                Log.d(TAG, "加载已保存的API密钥");
                editApiKey.setText(savedApiKey);
            } else {
                // 没有保存的API密钥，提示用户输入
                Log.d(TAG, "没有保存的API密钥，请用户输入");
                layoutApiKey.setError("请输入DeepSeek API密钥");
                Toast.makeText(requireContext(), "请配置您的DeepSeek API密钥", Toast.LENGTH_SHORT).show();
            }

            // 设置保存按钮点击事件
            btnSave.setOnClickListener(v -> {
                try {
                    saveApiKey();
                } catch (Exception e) {
                    Log.e(TAG, "保存API密钥异常: " + e.getMessage(), e);
                    Toast.makeText(requireContext(), "保存失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

            // 设置测试按钮点击事件
            btnTest.setOnClickListener(v -> {
                try {
                    testApiConnection();
                } catch (Exception e) {
                    Log.e(TAG, "测试连接异常: " + e.getMessage(), e);
                    btnTest.setEnabled(true);
                    btnTest.setText("测试连接");
                    Toast.makeText(requireContext(), "测试失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

            return root;
        } catch (Exception e) {
            Log.e(TAG, "创建视图异常：" + e.getMessage(), e);
            Toast.makeText(requireContext(), "界面加载错误，请联系开发者", Toast.LENGTH_LONG).show();
            return root;
        }
    }

    /**
     * 保存API密钥
     */
    private void saveApiKey() {
        try {
            String apiKey = editApiKey.getText().toString().trim();
            
            if (apiKey.isEmpty()) {
                layoutApiKey.setError("请输入API密钥");
                return;
            }
            
            Log.d(TAG, "保存用户输入的API密钥");
            // 保存API密钥
            DeepseekUtils.saveApiKey(requireContext(), apiKey);
            Toast.makeText(requireContext(), "API密钥已保存", Toast.LENGTH_SHORT).show();
            layoutApiKey.setError(null);
        } catch (Exception e) {
            Log.e(TAG, "保存API密钥异常：" + e.getMessage(), e);
            Toast.makeText(requireContext(), "保存失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 测试API连接
     */
    private void testApiConnection() {
        try {
            String apiKey = editApiKey.getText().toString().trim();
            
            if (apiKey.isEmpty()) {
                layoutApiKey.setError("请先输入API密钥");
                return;
            }
            
            // 检查API密钥格式
            if (!apiKey.startsWith("sk-")) {
                Log.e(TAG, "API密钥格式错误，应以sk-开头");
                Toast.makeText(requireContext(), "API密钥格式错误，应以sk-开头", Toast.LENGTH_LONG).show();
                layoutApiKey.setError("API密钥格式错误，应以sk-开头");
                return;
            }
            
            // 显示正在测试的提示
            btnTest.setEnabled(false);
            btnTest.setText("测试中...");
            
            // 保存API密钥以便测试
            DeepseekUtils.saveApiKey(requireContext(), apiKey);
            
            // 直接测试API调用
            Log.d(TAG, "开始测试API连接");
            Toast.makeText(requireContext(), "正在测试API连接...", Toast.LENGTH_SHORT).show();
            testApiWithNote();
        } catch (Exception e) {
            Log.e(TAG, "测试连接异常：" + e.getMessage(), e);
            btnTest.setEnabled(true);
            btnTest.setText("测试连接");
            Toast.makeText(requireContext(), "发生错误: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 使用笔记测试API
     */
    private void testApiWithNote() {
        Toast.makeText(requireContext(), "正在测试API连接...", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "开始笔记API测试");
        
        // 添加一个标志变量，避免同时显示成功和失败
        final boolean[] responseHandled = {false};
        
        DeepseekUtils.processNoteAsync(
                requireContext(),
                createDummyNote(),
                "请用一句话回复'API连接测试成功，笔记已提取'",
                true, // 使用chat API进行测试
                new DeepseekUtils.ApiCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        if (getActivity() == null || !isAdded() || responseHandled[0]) {
                            Log.d(TAG, "API测试成功但Fragment已不可见或响应已处理");
                            return;
                        }
                        
                        responseHandled[0] = true;
                        btnTest.setEnabled(true);
                        btnTest.setText("测试连接");
                        
                        Log.d(TAG, "API测试响应：" + result);
                        if (result != null && (result.contains("连接成功") || result.contains("API连接测试成功"))) {
                            Toast.makeText(requireContext(), "API连接测试成功", Toast.LENGTH_SHORT).show();
                        } else if (result != null && result.toLowerCase().contains("error")) {
                            Toast.makeText(requireContext(), "API返回错误: " + result, Toast.LENGTH_LONG).show();
                            layoutApiKey.setError("API返回错误，请检查密钥是否正确");
                        } else {
                            Toast.makeText(requireContext(), "API响应: " + result, Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(String error) {
                        if (getActivity() == null || !isAdded() || responseHandled[0]) {
                            Log.d(TAG, "API测试失败但Fragment已不可见或响应已处理");
                            return;
                        }
                        
                        responseHandled[0] = true;
                        btnTest.setEnabled(true);
                        btnTest.setText("测试连接");
                        
                        Log.e(TAG, "API测试失败：" + error);
                        
                        // 显示特定错误消息
                        String displayError = error;
                        if (error.contains("401") || error.contains("认证")) {
                            displayError = "API密钥认证失败，请检查密钥是否正确";
                            layoutApiKey.setError("API密钥无效");
                        } else if (error.contains("超时")) {
                            displayError = "API连接超时，请稍后重试";
                        } else if (error.contains("网络")) {
                            displayError = "网络连接问题，请检查网络设置";
                        }
                        
                        Toast.makeText(requireContext(), "连接失败: " + displayError, Toast.LENGTH_LONG).show();
                    }
                });
    }
    
    /**
     * 创建测试用的笔记对象
     */
    private com.example.neutonote2.data.model.NoteWithTags createDummyNote() {
        try {
            com.example.neutonote2.data.model.NoteWithTags noteWithTags = new com.example.neutonote2.data.model.NoteWithTags();
            noteWithTags.note = new com.example.neutonote2.data.model.Note("测试笔记", "这是一条测试笔记，用于测试DeepSeek API连接。", "");
            noteWithTags.tags = new java.util.ArrayList<>();
            return noteWithTags;
        } catch (Exception e) {
            Log.e(TAG, "创建测试笔记异常：" + e.getMessage(), e);
            // 创建备选测试笔记，避免空指针异常
            com.example.neutonote2.data.model.NoteWithTags fallbackNote = new com.example.neutonote2.data.model.NoteWithTags();
            fallbackNote.note = new com.example.neutonote2.data.model.Note("备用测试笔记", "这是备用测试内容", "");
            fallbackNote.tags = new java.util.ArrayList<>();
            return fallbackNote;
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        
        try {
            // 避免内存泄漏
            mainHandler.removeCallbacksAndMessages(null);
            
            // 重置按钮状态
            if (btnTest != null) {
                btnTest.setEnabled(true);
                btnTest.setText("测试连接");
            }
        } catch (Exception e) {
            Log.e(TAG, "销毁视图异常: " + e.getMessage(), e);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        
        try {
            // 关闭执行器
            if (executor != null && !executor.isShutdown()) {
                executor.shutdown();
                try {
                    // 等待任务完成
                    if (!executor.awaitTermination(2, TimeUnit.SECONDS)) {
                        executor.shutdownNow();
                    }
                } catch (InterruptedException e) {
                    executor.shutdownNow();
                    Thread.currentThread().interrupt();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "销毁异常: " + e.getMessage(), e);
        }
    }
} 